#!/bin/sh

# This file is part of netfilter-persistent
# (was iptables-persistent)
# Copyright (C) 2009, Simon Richter <sjr@debian.org>
# Copyright (C) 2010, 2014 Jonathan Wiltshire <jmw@debian.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.

set -e

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Exit fast if IPv6 is disabled
test -e /proc/sys/net/ipv6 || exit 0

# Source configuration
if [ -f "/etc/default/netfilter-persistent" ]; then
    . /etc/default/netfilter-persistent
fi

load_rules()
{
    if [ "${IP6TABLES_RESTORE_NOFLUSH}x" = "yesx" ]; then
        NOFLUSH='--noflush'
    else
        NOFLUSH=''
    fi

    #load IPv6 rules
    if [ ! -f /etc/iptables/rules.v6 ]; then
        echo "Warning: skipping IPv6 (no rules to load)"
    fi

    if [ "${IP6TABLES_TEST_RULESET}x" = "yesx" ] ; then
        if ! ip6tables-restore --test $NOFLUSH < /etc/iptables/rules.v6 ; then
            echo "Error: IPv6 rules failed test load. New rules NOT loaded"
            return
        fi
    fi

    ip6tables-restore $NOFLUSH < /etc/iptables/rules.v6
}

save_rules()
{
    if [ ! "${IP6TABLES_SKIP_SAVE}x" = "yesx" ]; then
        touch /etc/iptables/rules.v6
        ip6tables-save > /etc/iptables/rules.v6
        chmod 0640 /etc/iptables/rules.v6
    fi
}

flush_rules()
{
    TABLES=$(ip6tables-save | sed -E -n 's/^\*//p')
    for table in $TABLES
    do
        CHAINS=$(ip6tables-save -t $table | sed -E -n 's/^:([A-Z]+) [A-Z]+ .*/\1/p')
        for chain in $CHAINS
        do
            # policy can't be set on user-defined chains
            ip6tables -t $table -P $chain ACCEPT || true
        done
        ip6tables -t $table -F
        ip6tables -t $table -Z
        ip6tables -t $table -X
    done
}

case "$1" in
start|restart|reload|force-reload)
    load_rules
    ;;
save)
    save_rules
    ;;
stop)
    # Why? because if stop is used, the firewall gets flushed for a variable
    # amount of time during package upgrades, leaving the machine vulnerable
    # It's also not always desirable to flush during purge
    echo "Automatic flushing disabled, use \"flush\" instead of \"stop\""
    ;;
flush)
    flush_rules
    ;;
*)
    echo "Usage: $0 {start|restart|reload|force-reload|save|flush}" >&2
    exit 1
    ;;
esac
